package mysql

import (
	"easyShop/core/config"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"strconv"
)

type Database struct {
}

var conn *gorm.DB
var errorMsg string
var limit = 15
var page = 1

func SetConnect() (*gorm.DB, string) {
	if conn == nil {
		user := config.GetConfig("full_database.user").(string)
		pass := config.GetConfig("full_database.password").(string)
		host := config.GetConfig("full_database.host").(string)
		port := config.GetConfig("full_database.port").(string)
		dbName := config.GetConfig("full_database.db_name").(string)
		charset := config.GetConfig("full_database.charset").(string)
		dsn := user + ":" + pass + "@tcp(" + host + ":" + port + ")/" + dbName + "?charset=" + charset + "&parseTime=True&loc=Local"
		con, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
			SkipDefaultTransaction: true,
			Logger:                 logger.Default.LogMode(logger.Silent),
		})
		if err != nil {
			errorMsg = "链接数据库异常"
		}
		conn = con
	}

	return conn, errorMsg
}

func GetConnect() *gorm.DB {
	if conn == nil {
		errorMsg = "链接数据库异常"
	}
	return conn
}

func GetNewConnect() (*gorm.DB, error) {
	user := config.GetConfig("full_database.user").(string)
	pass := config.GetConfig("full_database.password").(string)
	host := config.GetConfig("full_database.host").(string)
	port := config.GetConfig("full_database.port").(string)
	dbName := config.GetConfig("full_database.db_name").(string)
	charset := config.GetConfig("full_database.charset").(string)
	dsn := user + ":" + pass + "@tcp(" + host + ":" + port + ")/" + dbName + "?charset=" + charset + "&parseTime=True&loc=Local"
	con, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: true,
		Logger:                 logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		return con, errors.New("链接数据库异常")
	}
	return con, nil
}

func GetConnectAndError() (*gorm.DB, string) {
	if conn == nil {
		errorMsg = "链接数据库异常"
	}
	return conn, errorMsg
}

func Start() (d *Database) {
	return new(Database)
}

func (*Database) Limit(i int) (d *Database) {
	limit = i
	return
}

func (*Database) Page(i int) (d *Database) {
	fmt.Print("page=", page)
	if i == 0 {
		page = 1
	} else {
		page = i
	}
	return
}

type Pagination struct {
	Total       int         `json:"total"`
	CurrentPage int         `json:"current_page"`
	LastPage    int         `json:"last_page"`
	Dest        interface{} `json:"list"`
}

func (*Database) Pagination(tx *gorm.DB, dest interface{}) Pagination {
	offset := (page - 1) * limit
	countTx := *tx
	var count64 int64
	countTx.Model(&dest).Count(&count64)
	count, _ := strconv.Atoi(strconv.FormatInt(count64, 10))
	tx.Limit(limit).Offset(offset).Find(&dest)
	lastPage := count / limit
	pagination := Pagination{Total: count, CurrentPage: page, LastPage: lastPage, Dest: dest}
	return pagination
}
